//
//  TcpClientUtil.m
//  TestTcpUdp
//
//  Created by leeson zhong on 2021/7/7.
//

#import "TcpClientUtil.h"
#import "GCDAsyncSocket.h"

@interface TcpClientUtil()<GCDAsyncSocketDelegate>{
    NSString *serverIp;
    int serverPort;
}

//客户端
@property (strong, nonatomic) GCDAsyncSocket *clientSocket;

@end

@implementation TcpClientUtil

-(BOOL)initWithServerIp:(NSString *)ip Port:(int)port{
    // 初始化服务端socket
    self.clientSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSError *error = nil;
    BOOL result = [self.clientSocket connectToHost:ip onPort:port error:&error];
    if (result == NO && self.delegate) {
        [self.delegate onTcpClientConnectServer:NO];
        self.clientSocket = nil;
        [self.delegate onTcpClientClose];
    }else{
        serverIp = ip;
        serverPort = port;
    }
    return result;
}

-(BOOL)sendData:(NSData *)data{
    if (self.clientSocket) {
        [self.clientSocket writeData:data withTimeout:-1 tag:0];
        return YES;
    }else{
        return NO;
    }
}

-(void)close{
    if (self.clientSocket) {
        [self.clientSocket disconnect];
    }
}

-(NSString *)getServerIp{
    return serverIp;
}
-(int)getServerPort{
    return serverPort;
}


#pragma mark GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    [self.clientSocket readDataWithTimeout:- 1 tag:0];
    if (self.delegate) {
        [self.delegate onTcpClientConnectServer:YES];
    }
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    if (self.delegate) {
        [self.delegate onTcpClientReceiveData:data ServerIp:serverIp ServerPort:serverPort];
    }
    //一直请求读取否则会接收不到数据
    [sock readDataWithTimeout:-1 tag:tag];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(nullable NSError *)err{
    if (self.delegate) {
        [self.delegate onTcpClientConnectServer:NO];
        self.clientSocket = nil;
        [self.delegate onTcpClientClose];
    }
}



@end
